package com.zzx.controller;

import com.mysql.cj.protocol.x.XMessage;
import com.zzx.Util.DateFormatUtil;
import com.zzx.Util.JSONUtil;
import com.zzx.Util.UserUtil;
import com.zzx.bean.*;
import com.zzx.service.imp.ExpressService;
import com.zzx.servlet.ResponseText;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @Author: Spider Man
 * @Description: 快递controller
 * @Date Created in 2020-09-14 8:29
 * @Modified By:
 */
public class ExpressController {

    ExpressService expressService = new ExpressService();

    @ResponseText("/express/console.do")
    public String console(HttpServletRequest request, HttpServletResponse response){
        List<Map<String,Integer>> list = expressService.console();
        Message message = new Message();
        if (list.size() == 0){
            message.setStatus(-1);
        }else {
            message.setStatus(0);
        }
        message.setData(list);
        return JSONUtil.toJSON(message);
    }

    @ResponseText("/express/list.do")
    public String list(HttpServletRequest request, HttpServletResponse response){
        // 1. 查询数据的起始索引值
        int offset = Integer.parseInt(request.getParameter("offset"));
        // 2. 当前页需要查询的数据量
        int pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
        // 3. 查询
        List<Express> list = expressService.findAllExpressInfo(true, offset, pageNumber);
        List<BootstrapTableExpress> list1 = new ArrayList<>();
        for (Express express : list) {
            String inTime = DateFormatUtil.format(express.getInTime());
            String outTime = express.getOutTime() == null?"未出库":DateFormatUtil.format(express.getOutTime());
            String status  = express.getStatus() == 0?"待取件":"已取件";
            String code = express.getCode() == null?"已取件": express.getCode();
            BootstrapTableExpress bootstrapTableExpress = new BootstrapTableExpress(express.getId(),express.getNumber(),
            express.getUsername(),express.getUserPhone(),express.getCompany(),code,inTime,outTime,status,express.getSysPhone());
            list1.add(bootstrapTableExpress);
        }
        List<Map<String, Integer>> console = expressService.console();
        Integer total = console.get(0).get("data1_size");
        // 4. 将list封装为bootstrap-table能够识别的格式
        ResultData<BootstrapTableExpress> data = new ResultData<>();
        data.setRows(list1);
        data.setTotal(total);
        return JSONUtil.toJSON(data);
    }

    @ResponseText("/express/insert.do")
    public String insert(HttpServletRequest request, HttpServletResponse response){
        String number = request.getParameter("number");
        String company = request.getParameter("company");
        String username = request.getParameter("username");
        String userPhone = request.getParameter("userPhone");

        Express express = new Express(number,username,userPhone,company, UserUtil.createSysPhone(request.getSession()));
        boolean flag = expressService.insert(express);
        Message message = new Message();
        if (flag){
            message.setStatus(0);
            message.setResult("快递录入成功!!");
        }else {
            message.setStatus(-1);
            message.setResult("快递录入失败!!");
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseText("/express/find.do")
    public String find(HttpServletRequest request, HttpServletResponse response){
        String number = request.getParameter("number");
        Express express = expressService.findExpressByNumber(number);
        Message message = new Message();
        if (express == null){
            message.setStatus(-1);
            message.setResult("单号不存在");
        }else {
            message.setStatus(0);
            message.setResult("查询成功");
            message.setData(express);
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseText("/express/update.do")
    public String update(HttpServletRequest request, HttpServletResponse response){
        int id = Integer.parseInt(request.getParameter("id"));
        String number = request.getParameter("number");
        String company = request.getParameter("company");
        String username = request.getParameter("username");
        String userPhone = request.getParameter("userPhone");
        int status = Integer.parseInt(request.getParameter("status"));

        Express express = new Express();
        express.setNumber(number);
        express.setCompany(company);
        express.setUsername(username);
        express.setUserPhone(userPhone);
        express.setStatus(status);

        boolean update = expressService.update(id, express);
        Message message = new Message();
        if (update){
            message.setStatus(0);
            message.setResult("修改成功");
        }else {
            message.setStatus(-1);
            message.setResult("修改失败");
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseText("/express/delete.do")
    public String delete(HttpServletRequest request, HttpServletResponse response){
        int id = Integer.parseInt(request.getParameter("id"));
        boolean flag = expressService.delete(id);
        Message message = new Message();
        if (flag){
            message.setStatus(0);
            message.setResult("删除成功");
        }else {
            message.setStatus(-1);
            message.setResult("删除失败");
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseText("/wx/findExpressByUPhone.do")
    public String findExpressByUPhone(HttpServletRequest request, HttpServletResponse response){
        User wxUser = UserUtil.getWxUser(request.getSession());
        Message message = new Message();
        try{
            String uPhone = wxUser.getuPhone();
            List<Express> list = expressService.findExpressByUserPhone(uPhone);
            List<BootstrapTableExpress> list1 = new ArrayList<>();
            for (Express express : list) {
                String inTime = DateFormatUtil.format(express.getInTime());
                String outTime = express.getOutTime() == null?"未出库":DateFormatUtil.format(express.getOutTime());
                String status  = express.getStatus() == 0?"待取件":"已取件";
                String code = express.getCode() == null?"已取件": express.getCode();
                BootstrapTableExpress bootstrapTableExpress = new BootstrapTableExpress(express.getId(),express.getNumber(),
                        express.getUsername(),express.getUserPhone(),express.getCompany(),code,inTime,outTime,status,express.getSysPhone());
                list1.add(bootstrapTableExpress);
            }
            if (list.size() == 0){
                message.setStatus(-1);
            }else {
                message.setStatus(0);
                Stream<BootstrapTableExpress> status0Express = list1.stream().filter(express -> {
                    if (express.getStatus().equals("待取件")) {
                        return true;
                    } else {
                        return false;
                    }
                }).sorted(((o1, o2) -> {
                    long o1Time = DateFormatUtil.toTime(o1.getInTime());
                    long o2Time = DateFormatUtil.toTime(o2.getInTime());
                    return (int)(o1Time-o2Time);
                }));
                Stream<BootstrapTableExpress> status1Express = list1.stream().filter(express -> {
                    if (express.getStatus().equals("已取件")) {
                        return true;
                    } else {
                        return false;
                    }
                }).sorted(((o1, o2) -> {
                    long o1Time = DateFormatUtil.toTime(o1.getInTime());
                    long o2Time = DateFormatUtil.toTime(o2.getInTime());
                    return (int)(o1Time-o2Time);
                }));
                Object[] status0 = status0Express.toArray();
                Object[] status1 = status1Express.toArray();
                Map data = new HashMap();
                data.put("status0",status0);
                data.put("status1",status1);
                message.setData(data);
            }
        }catch (NullPointerException e){
            message.setStatus(-2);
            message.setResult("查询异常");
        }
        return JSONUtil.toJSON(message.getData());
    }

    @ResponseText("/wx/userExpressList.do")
    public String userExpressList(HttpServletRequest request, HttpServletResponse response){
        String uPhone = request.getParameter("uPhone");
        List<Express> list = expressService.findExpressByUserPhoneAndStatus(uPhone, 0);
        List<BootstrapTableExpress> list1 = new ArrayList<>();
        for (Express express : list) {
            String inTime = DateFormatUtil.format(express.getInTime());
            String outTime = express.getOutTime() == null?"未出库":DateFormatUtil.format(express.getOutTime());
            String status  = express.getStatus() == 0?"待取件":"已取件";
            String code = express.getCode() == null?"已取件": express.getCode();
            BootstrapTableExpress bootstrapTableExpress = new BootstrapTableExpress(express.getId(),express.getNumber(),
                    express.getUsername(),express.getUserPhone(),express.getCompany(),code,inTime,outTime,status,express.getSysPhone());
            list1.add(bootstrapTableExpress);
        }
        Message message = new Message();
        if (list.size() == 0){
            message.setStatus(-1);
            message.setResult("未查询到快递信息");
        }else {
            message.setStatus(0);
            message.setResult("查询成功");
            message.setData(list1);
        }
        return JSONUtil.toJSON(message);
    }
}
